import { Product } from '../types/product';

const STORAGE_KEY = 'finance_products';
const REVERSE_CALCULATIONS_KEY = 'reverse_calculations';
const INVESTMENT_PLANS_KEY = 'investment_plans';

export interface InvestmentPlan {
  id: string;
  productId: string;
  principal: number;
  startDate: Date;
  endDate: Date;
  createdAt: Date;
}

export interface ReverseCalculation {
  id: string;
  productId: string;
  productName: string;
  bankName: string;
  startDate: Date;
  endDate: Date;
  principal: number;
  profit: number;
  actualRate: number;
  dailyProfit: number;
  periodDays: number;  // 添加投资天数字段
}

// 获取所有产品
export const getAllProducts = (): Product[] => {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    const products = data ? JSON.parse(data) : [];
    
    // 确保日期字段被正确解析
    return products.map((product: any) => ({
      ...product,
      createdAt: new Date(product.createdAt),
      updatedAt: new Date(product.updatedAt),
      historyRates: (product.historyRates || []).map((rate: any) => ({
        ...rate,
        startDate: new Date(rate.startDate),
        endDate: new Date(rate.endDate),
      })),
      investments: (product.investments || []).map((investment: any) => ({
        ...investment,
        purchaseDate: new Date(investment.purchaseDate),
        redeemDate: investment.redeemDate ? new Date(investment.redeemDate) : undefined,
      })),
    }));
  } catch (error) {
    console.error('获取产品数据失败:', error);
    return [];
  }
};

// 保存产品
export const saveProduct = (product: Product): void => {
  try {
    const products = getAllProducts();
    const index = products.findIndex(p => p.id === product.id);
    
    if (index !== -1) {
      products[index] = product;
    } else {
      products.push(product);
    }

    localStorage.setItem(STORAGE_KEY, JSON.stringify(products));
  } catch (error) {
    console.error('保存产品数据失败:', error);
    throw new Error('保存失败，请重试');
  }
};

// 删除产品
export const deleteProduct = (id: string): void => {
  try {
    const products = getAllProducts();
    const filtered = products.filter(p => p.id !== id);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered));
  } catch (error) {
    console.error('删除产品数据失败:', error);
    throw new Error('删除失败，请重试');
  }
};

// 获取单个产品
export const getProduct = (id: string): Product | null => {
  try {
    const products = getAllProducts();
    return products.find(p => p.id === id) || null;
  } catch (error) {
    console.error('获取产品数据失败:', error);
    return null;
  }
};

// 获取所有收益反算记录
export const getAllReverseCalculations = (): ReverseCalculation[] => {
  try {
    const data = localStorage.getItem(REVERSE_CALCULATIONS_KEY);
    if (!data) return [];
    
    const calculations = JSON.parse(data);
    if (!Array.isArray(calculations)) return [];
    
    // 确保日期字段被正确解析
    return calculations.map((calc: any) => {
      try {
        return {
          ...calc,
          principal: Number(calc.principal),
          profit: Number(calc.profit),
          actualRate: Number(calc.actualRate),
          dailyProfit: Number(calc.dailyProfit),
          startDate: new Date(calc.startDate),
          endDate: new Date(calc.endDate),
        };
      } catch (e) {
        console.error('解析收益反算数据失败:', e);
        return null;
      }
    }).filter((calc): calc is ReverseCalculation => calc !== null);
  } catch (error) {
    console.error('获取收益反算数据失败:', error);
    return [];
  }
};

// 保存收益反算记录
export const saveReverseCalculation = (calculation: ReverseCalculation): void => {
  try {
    const calculations = getAllReverseCalculations();
    const index = calculations.findIndex(c => c.id === calculation.id);
    
    // 创建一个用于保存的对象（不使用类型转换）
    const calcToSave = {
      ...calculation,
      startDate: calculation.startDate.toISOString(),
      endDate: calculation.endDate.toISOString()
    };
    
    // 更新或添加记录
    if (index !== -1) {
      // 更新现有记录
      const updatedCalcs = [...calculations];
      updatedCalcs[index] = {
        ...calculation,  // 保留原始类型
        startDate: new Date(calcToSave.startDate),
        endDate: new Date(calcToSave.endDate)
      };
      
      // 保存更新后的数组
      localStorage.setItem(REVERSE_CALCULATIONS_KEY, JSON.stringify(
        updatedCalcs.map(calc => ({
          ...calc,
          startDate: calc.startDate.toISOString(),
          endDate: calc.endDate.toISOString()
        }))
      ));
    } else {
      // 添加新记录
      calculations.push({
        ...calculation,  // 保留原始类型
        startDate: calculation.startDate,
        endDate: calculation.endDate
      });
      
      // 保存更新后的数组
      localStorage.setItem(REVERSE_CALCULATIONS_KEY, JSON.stringify(
        calculations.map(calc => ({
          ...calc,
          startDate: calc.startDate.toISOString(),
          endDate: calc.endDate.toISOString()
        }))
      ));
    }
  } catch (error) {
    console.error('保存收益反算数据失败:', error);
    throw new Error('保存失败，请重试');
  }
};

// 删除收益反算记录
export const deleteReverseCalculation = (id: string): void => {
  try {
    const calculations = getAllReverseCalculations();
    const filtered = calculations.filter(c => c.id !== id);
    localStorage.setItem(REVERSE_CALCULATIONS_KEY, JSON.stringify(filtered));
  } catch (error) {
    console.error('删除收益反算数据失败:', error);
    throw new Error('删除失败，请重试');
  }
};

// 获取所有投资计划
export const getAllInvestmentPlans = (): InvestmentPlan[] => {
  try {
    const data = localStorage.getItem(INVESTMENT_PLANS_KEY);
    if (!data) return [];

    const plans = JSON.parse(data);
    if (!Array.isArray(plans)) return [];
    
    // 确保日期字段被正确解析
    return plans.map((plan: any) => {
      try {
        return {
          id: plan.id,
          productId: plan.productId,
          principal: Number(plan.principal),
          startDate: new Date(plan.startDate),
          endDate: new Date(plan.endDate),
          createdAt: new Date(plan.createdAt),
        };
      } catch (e) {
        console.error('解析投资计划数据失败:', e);
        return null;
      }
    }).filter((plan): plan is InvestmentPlan => plan !== null);
  } catch (error) {
    console.error('获取投资计划数据失败:', error);
    return [];
  }
};

// 保存投资计划
export const saveInvestmentPlan = (plan: InvestmentPlan): void => {
  try {
    const plans = getAllInvestmentPlans();
    const index = plans.findIndex(p => p.id === plan.id);
    
    // 创建一个用于JSON序列化的对象
    const planForStorage = {
      ...plan,
      startDate: plan.startDate.toISOString(),
      endDate: plan.endDate.toISOString(),
      createdAt: plan.createdAt.toISOString()
    };
    
    if (index !== -1) {
      // 更新现有计划
      const updatedPlans = [...plans];
      updatedPlans[index] = plan; // 保持原始类型
      
      // 保存更新后的数组
      localStorage.setItem(INVESTMENT_PLANS_KEY, JSON.stringify(
        updatedPlans.map(p => ({
          ...p,
          startDate: p.startDate.toISOString(),
          endDate: p.endDate.toISOString(),
          createdAt: p.createdAt.toISOString()
        }))
      ));
    } else {
      // 添加新计划
      plans.push(plan); // 保持原始类型
      
      // 保存更新后的数组
      localStorage.setItem(INVESTMENT_PLANS_KEY, JSON.stringify(
        plans.map(p => ({
          ...p,
          startDate: p.startDate.toISOString(),
          endDate: p.endDate.toISOString(),
          createdAt: p.createdAt.toISOString()
        }))
      ));
    }
  } catch (error) {
    console.error('保存投资计划数据失败:', error);
    throw new Error('保存失败，请重试');
  }
};

// 删除投资计划
export const deleteInvestmentPlan = (id: string): void => {
  try {
    const plans = getAllInvestmentPlans();
    const filtered = plans.filter(p => p.id !== id);
    localStorage.setItem(INVESTMENT_PLANS_KEY, JSON.stringify(filtered));
  } catch (error) {
    console.error('删除投资计划数据失败:', error);
    throw new Error('删除失败，请重试');
  }
};